/**
 * 数据源
 * @Author: zhangshubin
 * @Date: 2023-12-20 09:14:58
 * @Last Modified by: zhangshubin
 * @Last Modified time: 2023-12-22 17:53:01
 *
 */
import {
  Button,
  Col,
  Dropdown,
  Form,
  Input,
  InputNumber,
  MenuProps,
  Modal,
  Radio,
  Select
} from 'antd'
import DraggableDialog from '../DraggableDialog'
import { useEffect, useRef, useState } from 'react'

import './index.less'

import * as DSApi from '@/api/dataSource'
// import { Icon } from '@iconify/react/dist/iconify.js'
// import plusIcon from '@iconify/icons-ph/plus'
// import minusIcon from '@iconify/icons-ph/minus'
// import DropdownButton from 'antd/es/dropdown/dropdown-button'

interface IProjectDialog {
  title?: string
  onClose?: () => void
  onOk?: (file: HFileMeta) => void
}

type FieldType = DSApi.DSource

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
}
const initFormValues = {
  name: '',
  url: '',
  refreshInterval: 3,
  varDefineType: 0,
  varDefine: ''
}

export default function DataSourceDialog(props: IProjectDialog) {
  const [form] = Form.useForm()
  // 是否为添加状态
  const [isEdit, setIsEdit] = useState(false)
  // 数据源列表
  const dsList = useRef<DSApi.DSource[]>([])
  // 数据源下拉选项
  const [dsOptionList, setDsOptionList] = useState([])
  // 当前选中的数据源
  const [selectDsId, setSelectDsId] = useState(0)
  // 当前选择的操作状态
  const [selectOprType, setSelectOprType] = useState('')
  // 当前选择的操作状态字符串
  const [selectOprTypeStr, setSelectOprTypeStr] = useState('操作')

  // 命令菜单
  const menus: MenuProps['items'] = [
    {
      label: <span className="font-size-12px">新增</span>,
      key: 'add'
    },
    {
      label: <span className="font-size-12px">修改</span>,
      key: 'modify'
    },
    {
      label: <span className="font-size-12px">删除</span>,
      key: 'delete'
    }
  ]
  /**
   * 保存
   */
  const onSave = () => {
    form.validateFields().then(async (values: any) => {
      let result
      if (!selectDsId) {
        result = await DSApi.createDataSource(values)
      } else {
        values.id = selectDsId
        result = await DSApi.updateDataSource(values)
      }
      if (result) {
        props.onClose && props.onClose()
      }
    })
  }

  //获取数据源列表
  const getDataSourceList = async () => {
    const result = await DSApi.getDataSourcePage({
      pageNo: 1,
      pageSize: 50
    })
    const { list } = result
    dsList.current = list
    if (list.length > 0) {
      setSelectDsId(list[0].id)
      form.setFieldValue('name', list[0].name)
    }
    const options = list.map((n: any) => {
      return {
        label: n.name,
        value: n.id
      }
    })
    setDsOptionList(options)
  }

  // 当点击数据操作
  const onClickOprBtn = (optType?: string) => {
    optType = optType ? optType : selectOprType
    if (optType == 'delete' || optType == 'modify') {
      const ds = dsList.current.find((n) => n.id == selectDsId)
      if (!ds) {
        return
      }
      if (optType == 'delete') {
        deleteDs(ds)
      } else if (optType == 'modify') {
        form.setFieldValue('name', ds.name)
      }
    } else if (optType == 'add') {
      // 现在模式
      setSelectDsId(0)
      form.setFieldsValue(initFormValues)
    }
  }
  //当选择操作
  const onSelectOprType = (key: string) => {
    let str = '操作'
    if (key == 'add') {
      str = '新增'
    } else if (key == 'modify') {
      str = '修改'
    } else if (key == 'delete') {
      str = '删除'
    }
    setSelectOprTypeStr(str)
    // 设置编辑状态
    setIsEdit(key == 'modify' || key == 'add' ? true : false)
    // 记录操作状态
    setSelectOprType(key)
    onClickOprBtn(key)
  }

  //删除树数据源
  const deleteDs = (ds: DSApi.DSource) => {
    Modal.confirm({
      content: `确认删除数据源-${ds.name}么`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        doDelete(ds.id)
      },
      onCancel() {}
    })
  }
  // 执行删除数据源操作
  const doDelete = async (id: number) => {
    DSApi.deleteDataSource(id).then(() => {
      getDataSourceList()
    })
  }

  useEffect(() => {
    getDataSourceList()
  }, [])

  return (
    <DraggableDialog
      title="数据源管理"
      open={true}
      onCancel={props.onClose}
      width={450}
      footer={[
        <Button
          key="cancle"
          size="small"
          className="font-size-12px! mr-20px"
          onClick={(e) => props.onClose && props.onClose()}
        >
          取消
        </Button>,
        <Button
          type="primary"
          key="ok"
          size="small"
          className="font-size-12px!"
          onClick={(e) => onSave()}
        >
          确定
        </Button>
      ]}
    >
      <Form
        name="dsForm"
        layout="horizontal"
        form={form}
        {...layout}
        size="small"
        initialValues={initFormValues}
        autoComplete="off"
      >
        <Form.Item label="名称">
          <Form.Item<FieldType>
            name="name"
            rules={[{ required: true, message: '名称不能为空' }]}
            noStyle
          >
            {!isEdit ? (
              <Select
                className="h-26px w-200px!"
                options={dsOptionList}
                value={selectDsId}
                onChange={(value) => setSelectDsId(value)}
              />
            ) : null}
            {isEdit ? <Input className="h-26px w-200px!" /> : null}
          </Form.Item>

          <Dropdown menu={{ items: menus, onClick: (e) => onSelectOprType(e.key) }}>
            <Button type="link" onClick={() => onClickOprBtn()}>
              {selectOprTypeStr}
            </Button>
          </Dropdown>
          {isEdit ? (
            <Button
              type="link"
              onClick={() => {
                onSelectOprType('')
              }}
            >
              退出编辑
            </Button>
          ) : null}
        </Form.Item>

        <Form.Item<FieldType>
          label="服务地址"
          name="url"
          rules={[{ required: true, message: '服务地址不能为空' }]}
          className="font-size-12px!"
        >
          <Input className="h-26px" />
        </Form.Item>

        <Form.Item<FieldType> label="刷新间隔" name="refreshInterval" rules={[{ required: true }]}>
          <InputNumber addonAfter="秒" />
        </Form.Item>

        <Form.Item<FieldType> label="类型" name="varDefineType">
          <Radio.Group>
            <Radio value={0}> 物模型</Radio>
            <Radio value={1}> 自定义</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item<FieldType> label="JSON" name="varDefine" rules={[{ required: false }]}>
          <Input.TextArea rows={5} />
        </Form.Item>
      </Form>
    </DraggableDialog>
  )
}
